package org.xp.judgeplatform.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.xp.judgeplatform.mapper.UserMapper;
import org.xp.judgeplatform.pojo.entity.User;

/**
 * 自定义UserDetailsService实现
 * 用于从数据库加载用户信息
 */
@Service
@Slf4j
@AllArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // DEBUG级别：用户加载过程（频繁操作）
        log.debug("正在加载用户: {}", username);
        
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        
        User user = userMapper.selectOne(queryWrapper);
        
        if (user == null) {
            log.warn("用户未找到: {}", username);
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        // DEBUG级别：用户加载成功
        log.debug("用户 {} 加载成功，角色: {}", username, user.getRole());
        
        // 返回自定义的UserPrincipal对象，包含完整的User实体信息
        return new UserPrincipal(user);
    }
} 